import wsgiref.handlers
from google.appengine.ext import webapp




from xmw import tianya
import xmw
from google.appengine.ext import db
class MainPage(xmw.RequestHandler):


    def get_thread(self,status):
        """
        q = tianya.TianyaThread.all()
        #q.filter('status != ', xmw.Thread_Status.BAD)
        q.filter(' hot <= ',0)
        thread = q.get()
        return thread
        
        """
        q = db.GqlQuery("SELECT * FROM TianyaThread"+
                        " WHERE status =:1 "+
                        #"AND hot> :2 "+
                        "order by hot ASC",
                        #status,0)
                        status)
        lst_thread=q.fetch(1)
        if lst_thread is None:
            return None
        if len(lst_thread) ==0:
            return None
        
        return lst_thread[0]
    
    def ping(self,thread):
        if thread is not None:
            try:
                page=thread.get_first_page()
            except:
                thread.hot=thread.hot-2
                if thread.hot<=-20:
                    thread.status=xmw.Thread_Status.BAD
                thread.put()        
                e=xmw.error.OK("thread set to bad,thread_id:%s"%thread.thread_id)
                self.render_error(e)
                return
            """
            if thread.hot<0:
                thread.hot=2
            else:
                thread.hot=thread.hot-1
            """
            thread.hot=thread.hot-1
            thread.put()
            
            e = xmw.error.OK("processed thread hot = %d,thread_id:%s"%(thread.hot,thread.thread_id))
            self.render_error(e)
            return
        
    def get(self):
        thread = self.get_thread(xmw.Thread_Status.INIT)
        if thread is not None:
            self.ping(thread)
        else:
            thread =self.get_thread(xmw.Thread_Status.RUN)
            if thread is not None:
                self.ping(thread)
            else:

                e = xmw.error.OK("NO thread to ping")
                self.render_error(e)
                return

        
    
def main():
    application = webapp.WSGIApplication(
                                       [('/robot/ping', MainPage)],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
